package org.jgs1904.apachepoidemo.utils;

import com.sun.deploy.net.HttpResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.CORBA.portable.OutputStream;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Excel 网络导出
 *
 * @author: 默苍璃
 * @date: 2023-10-09 18:10
 */
@Component
public class ExcelExportExample {

    public void excelExportExample(HttpServletResponse response) throws IOException {
        // 创建工作簿和表格
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建行和单元格，并设置数据
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello, World!");

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);

        // 设置 HTTP 响应头
        String fileName = "excel_export.xlsx";
        byte[] excelBytes = outputStream.toByteArray();

        // 设置响应类型为 Excel 文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        // 设置下载的文件名
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 从字节数组输出流将数据发送到网络输出流
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(excelBytes);

        // 刷新输出流
        responseOutputStream.flush();

        // 关闭输出流
        responseOutputStream.close();

        System.out.println("Excel 文件已成功导出到网络。");
    }

}
